package plugins.AI;

import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.gpt.IGPTAction;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.json.simple.JSONArray;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GetData_Report_Day implements IGPTAction {
    @Override
    public Map<String, String> invokeAction(String action, Map<String, String> params) {
        Map<String , String> result = new HashMap<>();
        if ("GET_Data".equalsIgnoreCase(action)) {

            // 获取当前用户的用户名
            String currentName = RequestContext.get().getUserName();

            String userselectFields = "name," +
                    "dcb4_sex," +
                    "dcb4_jiguan," +
                    "dcb4_height," +
                    "dcb4_weight," +
                    "dcb4_warn," +
                    "dcb4_bmi," +
                    "dcb4_healthylevel";

            //获取DynamicObject列表dcb4_userdata
            DynamicObject[] user = BusinessDataServiceHelper.load(
                    "dcb4_userdata", userselectFields, (new QFilter("name", QCP.is_notnull, null)).toArray()
            );

            String orderselectFields = "dcb4_buyer," +
                    "dcb4_date," +
                    "dcb4_time," +
                    "dcb4_merchant.name," +
                    "dcb4_purchased_dishes.dcb4_dishes";

            // 获取当前日期（不含时间）
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date today = calendar.getTime();

            // 日期范围条件（当天）
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date tomorrow = calendar.getTime();
            QFilter dateFilter = new QFilter("dcb4_date", QCP.large_equals, today).and(new QFilter("dcb4_date", QCP.less_than, tomorrow));

            // 组合买家条件和日期条件
            QFilter combinedFilter = new QFilter("dcb4_buyer", QCP.equals, currentName)
                    .and(dateFilter);

            // 执行查询
            DynamicObject[] orderHistory = BusinessDataServiceHelper.load(
                    "dcb4_order_history",
                    orderselectFields,
                    combinedFilter.toArray()
            );

            String dishesselectFields = "dcb4_merchant.name," +
                    "dcb4_merchant.dcb4_manager_name," +
                    "name," +
                    "dcb4_material," +
                    "dcb4_nutritionfactslist.dcb4_project," +
                    "dcb4_nutritionfactslist.dcb4_contain," +
                    "dcb4_nutritionfactslist.dcb4_nvr," ;

            //获取DynamicObject列表dcb4_dishes
            DynamicObject[] dishes = BusinessDataServiceHelper.load(
                    "dcb4_dishes", dishesselectFields, ((new QFilter("name", QCP.is_notnull, null))).toArray()
            );

            // 获取

            //创建一个JsonArray
            JSONArray jsonArray = new JSONArray();
            for (DynamicObject dynamicObject : user) {
                //将符合评价的信息加入JSONArray
                if (currentName.contains(dynamicObject.getString("name"))) {
                    JSONObject userData = new JSONObject();
                    userData.put("name", dynamicObject.getString("name"));
                    userData.put("sex", dynamicObject.getString("dcb4_sex"));
                    userData.put("jiguan", dynamicObject.get("dcb4_jiguan"));
                    userData.put("height", dynamicObject.getString("dcb4_height"));
                    userData.put("weight", dynamicObject.getString("dcb4_weight"));
                    userData.put("warn", dynamicObject.get("dcb4_warn"));
                    userData.put("bmi", dynamicObject.getString("dcb4_bmi"));
                    userData.put("healthylevel", dynamicObject.getString("dcb4_healthylevel"));

                    jsonArray.add(userData);
                }
            }


            JSONArray userOrderHistory = new JSONArray();
            for (DynamicObject order : orderHistory){
                JSONObject OrderHistory = new JSONObject();
                OrderHistory.put("buyer", order.get("dcb4_buyer"));
                OrderHistory.put("merchant", order.get("dcb4_merchant.name"));
                OrderHistory.put("date", order.get("dcb4_date"));
                OrderHistory.put("time", order.get("dcb4_time"));

                // 处理dcb4_purchased_dishes字段，假设它是一个嵌套的DynamicObject
                JSONArray purdishedDishesData = new JSONArray();
                DynamicObjectCollection purchasedDishes = order.getDynamicObjectCollection("dcb4_purchased_dishes");
                // userOrderHistory.put("dishes", order.getString("dcb4_purchased_dishes.dcb4_dishes.name"));

                for (DynamicObject purchasedDish : purchasedDishes) {
                    JSONObject dishJson = new JSONObject();
                    dishJson.put("purchasedDishes", purchasedDish.getString("dcb4_dishes.name"));
                    purdishedDishesData.add(dishJson);
                }

                OrderHistory.put("purchasedDishes", purdishedDishesData);

                userOrderHistory.add(OrderHistory);
            }
            jsonArray.add(userOrderHistory);


            JSONArray DishNutritionFactsList = new JSONArray();
            for (DynamicObject dish : dishes){
                JSONObject Dishes = new JSONObject();
                Dishes.put("merchant", dish.getString("dcb4_merchant.name"));
                Dishes.put("name", dish.getString("name"));


                // 处理dcb4_nutritionfactslist字段，假设它是一个嵌套的DynamicObjectCollection
                JSONArray nutritionFactsList = new JSONArray();
                DynamicObjectCollection nutritionFacts = dish.getDynamicObjectCollection("dcb4_nutritionfactslist");

                for (DynamicObject nutritionFact : nutritionFacts) {
                    JSONObject nutritionJson = new JSONObject();
                    nutritionJson.put("project", nutritionFact.getString("dcb4_project"));
                    nutritionJson.put("contain", nutritionFact.getString("dcb4_contain"));
                    nutritionJson.put("nvr", nutritionFact.getString("dcb4_nvr"));
                    nutritionFactsList.add(nutritionJson);
                }
                Dishes.put("nutritionFactsList", nutritionFactsList);


                // 将菜品信息加入JSONArray
                DishNutritionFactsList.add(Dishes);

            }
            jsonArray.add(DishNutritionFactsList);

            System.out.println(jsonArray.toJSONString());

            result.put("resultDynamicObject", jsonArray.toJSONString());
        }
        return result;
    }
}
